//
//  MainTabBarController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/12.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "MainTabBarController.h"

/**
 main
 */
#import "MainNavigationController.h"
#import "MainViewController.h"

/**
 userCenter
 */
#import "UserCenterNavigationController.h"
#import "UserCenterController.h"

//产业列表
#import "IndustryNavigationController.h"
#import "BCIndustryController.h"

//发现
#import "DiscoveryNavigationController.h"
#import "BCDiscoveryController.h"

//兑换
#import "MainConversionNavigationController.h"
#import "MainConversionController.h"

//充币提币
#import "BChargeCashNavigationController.h"
#import "BChargeCashController.h"


//login
#import "GSCommonLoginViewController.h"

#import "BCAppDelegate+PrivateMethod.h"

//
#import "BCUserOverdueController.h"

//sm
#import "BCAPPLaunchManager.h"
#import "BCAppVersionManager.h"//转换界面控制

//启动广告展示
#import "BCLaunchAdsController.h"

#import <Lottie/LOTAnimationView.h>

@interface MainTabBarController () <UITabBarControllerDelegate>

/**
 显示的tabBarController的控制器
 */
@property (nonatomic, strong) MainNavigationController *homeNavi;
@property (nonatomic, strong) IndustryNavigationController *industryNavi;
@property (nonatomic, strong) DiscoveryNavigationController *discoveryNavi;
@property (nonatomic, strong) UserCenterNavigationController *userCenterNavi;

//
@property (nonatomic, strong) MainConversionNavigationController *conversionNavi;
@property (nonatomic, strong) BChargeCashNavigationController *chargeCashNavi;


#pragma mark - views

/**
 *过度的启动页
 */
@property (nonatomic, weak) UIView *launchView;

/**
 *requestLaunchErrorFlag
 */
@property (nonatomic, assign) BOOL requestLaunchErrorFlag;

@end

@implementation MainTabBarController

/**
 屏幕方向处理
 */
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)shouldAutorotate {
    return false;
}


#pragma mark - viewControllers
/**
 main
 */
- (MainNavigationController *)mainVC {
    MainViewController *main = [MainViewController new];
    MainNavigationController *nav = [[MainNavigationController alloc] initWithRootViewController:main];
    nav.navigationBar.hidden = true;
    nav.tabBarItem.title = BCLocalizedKey(@"tabBar_home");
    nav.tabBarItem.image = [LOAD_IMAGE(@"tabBar_home_normal") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.selectedImage = [LOAD_IMAGE(@"tabBar_home_select") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.imageInsets = [self tabBarItemImageInsets];
    return nav;
}
/**
 userCenter
 */
- (UserCenterNavigationController *)userCenter {
    UserCenterController *uc = [UserCenterController new];
    UserCenterNavigationController *nav = [[UserCenterNavigationController alloc] initWithRootViewController:uc];
    nav.navigationBar.hidden = true;
    nav.tabBarItem.title = BCLocalizedKey(@"tabBar_menbers");
    nav.tabBarItem.image = [LOAD_IMAGE(@"tabBar_menbers_normal") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.selectedImage = [LOAD_IMAGE(@"tabBar_menbers_select") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.imageInsets = [self tabBarItemImageInsets];
    return nav;
}
/**
 industry
 */
- (IndustryNavigationController *)industry {
    BCIndustryController *inds = [BCIndustryController new];
    IndustryNavigationController *nav = [[IndustryNavigationController alloc] initWithRootViewController:inds];
    nav.navigationBar.hidden = true;
    nav.tabBarItem.title = BCLocalizedKey(@"tabBar_industry");
    nav.tabBarItem.image = [LOAD_IMAGE(@"tabBar_industry_normal") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.selectedImage = [LOAD_IMAGE(@"tabBar_industry_select") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.imageInsets = [self tabBarItemImageInsets];
    return nav;
}
/**
 industry
 */
- (DiscoveryNavigationController *)discovery {
    BCDiscoveryController *dis = [BCDiscoveryController new];
    DiscoveryNavigationController *nav = [[DiscoveryNavigationController alloc] initWithRootViewController:dis];
    nav.navigationBar.hidden = true;
    nav.tabBarItem.title = BCLocalizedKey(@"tabBar_discovery");
    nav.tabBarItem.image = [LOAD_IMAGE(@"tabBar_discovery_normal") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.selectedImage = [LOAD_IMAGE(@"tabBar_discovery_select") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.imageInsets = [self tabBarItemImageInsets];
    return nav;
}
//兑换
- (MainConversionNavigationController *)conversion {
    MainConversionController *conversion = [MainConversionController new];
    MainConversionNavigationController *nav = [[MainConversionNavigationController alloc] initWithRootViewController:conversion];
    nav.navigationBar.hidden = true;
    nav.tabBarItem.title = BCLocalizedKey(@"Conversion");
    nav.tabBarItem.image = [LOAD_IMAGE(@"tabBar_conversion_normal") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.selectedImage = [LOAD_IMAGE(@"tabBar_conversion_select") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.imageInsets = [self tabBarItemImageInsets];
    return nav;
}
//充提币
- (BChargeCashNavigationController *)chargeCash {
    BChargeCashController *chargeCashVC = [BChargeCashController new];
    BChargeCashNavigationController *nav = [[BChargeCashNavigationController alloc] initWithRootViewController:chargeCashVC];
    nav.navigationBar.hidden = true;
    nav.tabBarItem.title = BCLocalizedKey(@"Charge-Cash");
    nav.tabBarItem.image = [LOAD_IMAGE(@"tabBar_charge_normal") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.selectedImage = [LOAD_IMAGE(@"tabBar_charge_select") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.imageInsets = [self tabBarItemImageInsets];
    return nav;
}

#pragma mark - getter
- (MainNavigationController *)homeNavi {
    if (!_homeNavi) {
        _homeNavi = [self mainVC];
    }
    return _homeNavi;
}
- (IndustryNavigationController *)industryNavi {
    if (!_industryNavi) {
        _industryNavi = [self industry];
    }
    return _industryNavi;
}
- (DiscoveryNavigationController *)discoveryNavi {
    if (!_discoveryNavi) {
        _discoveryNavi = [self discovery];
    }
    return _discoveryNavi;
}
- (UserCenterNavigationController *)userCenterNavi {
    if (!_userCenterNavi) {
        _userCenterNavi = [self userCenter];
    }
    return _userCenterNavi;
}
- (MainConversionNavigationController *)conversionNavi {
    if (!_conversionNavi) {
        _conversionNavi = [self conversion];
    }
    return _conversionNavi;
}
- (BChargeCashNavigationController *)chargeCashNavi {
    if (!_chargeCashNavi) {
        _chargeCashNavi = [self chargeCash];
    }
    return _chargeCashNavi;
}

#pragma mark - setControllers
- (NSArray *)customViewControllers {
    //判断是否显示转换视图
    BOOL normalUI = [BCAppVersionManager sharedManager].showNormalUI;
    if (normalUI) {
        return @[self.homeNavi,self.industryNavi,self.userCenterNavi];
    }else {
        return @[self.conversionNavi,self.chargeCashNavi,self.userCenterNavi];
    }
}
- (void)setupCustoms {
    if (self.launchView) {
        [self.launchView removeFromSuperview];
        self.launchView = nil;
    }
    //
    self.tabBar.hidden = false;
    self.viewControllers = [self customViewControllers];
}
- (void)setTabBarAppearance {
    self.tabBar.hidden = false;
    //apperence
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor qmui_colorWithHexString:@"#C8C7CC"],NSFontAttributeName:[UIFont systemFontOfSize:13 weight:UIFontWeightMedium]} forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor darkMainColor],NSFontAttributeName:[UIFont systemFontOfSize:13 weight:UIFontWeightMedium]} forState:UIControlStateSelected];
    [[UITabBarItem appearance] setTitlePositionAdjustment:UIOffsetMake(0, -6)];
    //
    self.tabBar.backgroundImage = [UIImage qmui_imageWithColor:[UIColor whiteColor]];
    self.tabBar.shadowImage = [UIImage qmui_imageWithColor:[UIColor whiteColor]];
    self.tabBar.layer.shadowColor = RGBHEXA(0x000000, .1).CGColor;
    self.tabBar.layer.shadowOpacity = 1;
    self.tabBar.layer.shadowRadius = 5.0;
    self.tabBar.layer.shadowOffset = CGSizeMake(0, -1);
}
- (UIEdgeInsets)tabBarItemImageInsets {
    return UIEdgeInsetsMake(-6, 0, 6, 0);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.delegate = self;
    //
    [self setTabBarAppearance];
    self.tabBar.hidden = true;
    //监听网络状态变化 主要用于第一次预装app访问网络导致失败 需要主动刷新
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStatusChangedNotification) name:NetworkReachabilityStatusChangedNotification object:nil];
    //
    [self launchAppAction];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

#pragma mark - UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    /**
     如果是充提币controller时
     */
    if ([viewController isKindOfClass:BChargeCashNavigationController.class]) {
        //如果没有登录需要登录
        if (![BCUserManager sharedUser].isLogin) {
            [GSCommonLoginViewController presentToCommloginController:self];
            return false;
        }
    }
    return true;
}

#pragma mark - 关于启动流程处理
- (void)launchAppAction {
    //判断是否是启动app
    if ([BCAPPLaunchManager sharedLaunch].isLaunched) {
        [self loadMainUI:false];
    }else {
        [BCAPPLaunchManager sharedLaunch].isLaunched = true;
        //获取启动页视图 产生还在等待启动的效果
        UIStoryboard *launchScreen = [UIStoryboard storyboardWithName:@"LaunchScreen" bundle:nil];
        UIViewController *launchScreenController = [launchScreen instantiateViewControllerWithIdentifier:@"LaunchScreen"];
        UIView *launchView = launchScreenController.view;
        //获取到启动页的logoIV
        UIImageView *logoIV = [launchView viewWithTag:100];
        logoIV.alpha = 0;
        //
        [self.view addSubview:launchView];
        self.launchView = launchView;
        //
        LOTAnimationView *animationView = [LOTAnimationView animationNamed:@"F3_launch_source.json"];
        animationView.tag = 50;
        [self.launchView addSubview:animationView];
        [animationView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.centerY.mas_equalTo(self.launchView);
            make.width.height.mas_equalTo(550.0/3);
        }];
        WEAK_SELF
        [animationView playWithCompletion:^(BOOL animationFinished) {
            [wself launchWithLaunchView:wself.launchView];
        }];
    }
}
/**
 处理转换界面 BCAppVersionManager
 */
- (void)launchWithLaunchView:(UIView *)launchView {
    //是否需要请求启动 来判断展示界面
    BOOL needRequestLaunch = [BCAppVersionManager sharedManager].needRequestLaunch;
    if (needRequestLaunch) {
        [self requestLaunchData];
    }else {//不需要
        //判断展示什么界面
        [self toSwitchUI];
        //请求一次转换界面数据
        [[BCAppVersionManager sharedManager] requestAppVersionDataComplete:^(BConfigVersionData * _Nonnull data, NSError * _Nonnull error) {
        }];
    }
}
/**
 请求数据以展示界面
 */
- (void)requestLaunchData {
    //请求转换界面数据
    WEAK_SELF
    [[BCAppVersionManager sharedManager] requestAppVersionDataComplete:^(BConfigVersionData * _Nonnull data, NSError * _Nonnull error) {
        if (error) {//请求错误后 无法进入应用
            [wself requestLaunchDataError:error];
        }
        if (data) {//判断展示什么页面
            [wself toSwitchUI];
        }
    }];
}
/**
 启动请求错误提示用户后续操作
 */
- (void)requestLaunchDataError:(NSError *)error {
    [self.launchView removeFromSuperview];
    self.launchView = nil;
    //
    self.requestLaunchErrorFlag = true;
    [self.view bc_showError:error needRefresh:true refreshTitle:nil target:self refreshAction:@selector(requestLaunchDataErrorRefreshAction)];
}
- (void)requestLaunchDataErrorRefreshAction {
    self.requestLaunchErrorFlag = false;
    [self.view bc_hiddenError];
    //
    [self.view bc_showLoading];
    //请求转换界面数据
    WEAK_SELF
    [[BCAppVersionManager sharedManager] requestAppVersionDataComplete:^(BConfigVersionData * _Nonnull data, NSError * _Nonnull error) {
        [wself.view bc_hiddenLoading];
        if (error) {//请求错误后 无法进入应用
            [wself requestLaunchDataError:error];
        }
        if (data) {//判断展示什么页面
            [wself toSwitchUI];
        }
    }];
}
/**
 网络状态变化的通知 如果 处于请求失败界面刷新
 */
- (void)networkStatusChangedNotification {
    if (self.requestLaunchErrorFlag) {
        [self requestLaunchDataErrorRefreshAction];
    }
}

/**
 展示什么界面
 */
- (void)toSwitchUI {
    BOOL normalUI = [BCAppVersionManager sharedManager].showNormalUI;
    if (normalUI) {
        /**
         处理是否需要加载启动广告
         */
        BCAdsDataModel *launchAd = [BCAdsManager shared].launchAdModel;
        if (launchAd) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.launchView removeFromSuperview];
                self.launchView = nil;
                WEAK_SELF
                [BCLaunchAdsController showFromController:self adModel:launchAd complete:^{
                    [wself loadMainUI:true];
                }];
            });
        }else {
            //获取到显示animationView
            UIView *animationView = [self.launchView viewWithTag:50];
            //
            NSTimeInterval delayTime = 1.5;
            [UIView animateWithDuration:delayTime animations:^{
                animationView.alpha = 0;
            }];
            [UIView animateWithDuration:.1 delay:delayTime options:UIViewAnimationOptionCurveEaseOut animations:^{
                self.launchView.alpha = 0;
            } completion:^(BOOL finished) {
                [self.launchView removeFromSuperview];
                self.launchView = nil;
            }];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self loadMainUI:true];
            });
        }
        //请求广告数据啊
        [[BCAdsManager shared] requestAdsData];
    }else {
        [self.launchView removeFromSuperview];
        self.launchView = nil;
        [self loadMainUI:true];
    }
}

#pragma mark - private Method
//显示一次登录界面
- (void)showOnceLogin {
    /**
     当应用启动后 如果用户没有登录 并且有lastLoginUser的记录默认提示一次登录
     */
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (![BCUserManager sharedUser].isLogin && [BCUserLoginManager sharedLogin].lastUserInfo.sub.length) {
            [GSCommonLoginViewController presentToCommloginController:self];
        }
    });
}
/**
 加载主要UI
 */
- (void)loadMainUI:(BOOL)appLaunch {
    BOOL shouldShowOnceLogin = false;
    if (appLaunch) {
        if ([BCUserManager sharedUser].isLogin) {
            [[BCUserManager sharedUser] clearLoginUser];
            shouldShowOnceLogin = true;
        }
    }
    //设置控制器
    [self setupCustoms];
    //添加监听
    [self addNotifications];
    //
    if (shouldShowOnceLogin) {
        /**
         如果上次有用户登录 是在没有主动退出的情况下显示一次登录界面
         */
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self showOnceLogin];
        });
    }
}

#pragma mark - notifications
- (void)addNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userManagerUserLoginOverdueNotification:) name:BCUserManagerUserLoginOverdueNotification object:nil];
    //用户退出到后台太长时间 注销登录
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userEnterBackgroundLongTimeNotification:) name:BCUserEnterBackgroundLongTimeNotification object:nil];
    //监听首页切换区域
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeRegionChangedNotification:) name:HomeRegionChangedNotification object:nil];
    //用户切换语言
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userSettingLanguageChangedNotification:) name:UserSettingLanguageChangedNotification object:nil];
}



#pragma mark - userManagerUserLoginOverdueNotification:
/**
 用户登录过期或者在其他地方登录过后都会走这个通知 用户信息已经清空 需要用户回到相应的界面去重新登录
 */
- (void)userManagerUserLoginOverdueNotification:(NSNotification *)noti {
    //首先清空掉所有不是main的window
    BCAppDelegate *appDelegate = (BCAppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate showMainWindow];
    //弹出提示控制器 提示用户知道或者直接去重新登录
    id object = noti.object;
    NSError *err = nil;
    if ([object isKindOfClass:NSError.class]) {
        err = object;
    }
    //尝试过用 UIAlertController 太多问题了 还是自定义一个Window 弹出吧
    WEAK_SELF
    [BCUserOverdueController showOverdureWithError:err complete:^(BOOL clickedSure, BOOL clickedLogin) {
        if (clickedSure) {//直接返回
            [wself toCurrentNavigationControllerNeedLogin:false];
        }
        if (clickedLogin) {//需要弹出登录界面登录
            [wself toCurrentNavigationControllerNeedLogin:true];
        }
    }];
}
- (void)userEnterBackgroundLongTimeNotification:(NSNotification *)noti {
    //首先清空掉所有不是main的window
    BCAppDelegate *appDelegate = (BCAppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate showMainWindow];
    //
    [self toCurrentNavigationControllerNeedLogin:true];
}


//登录错误后 重置返回当前controller
- (void)toCurrentNavigationControllerNeedLogin:(BOOL)needLogin {
    //当前顶层控制器
    UIViewController *visibleController = [QMUIHelper visibleViewController];
    //main 当前的navi
    UINavigationController *currentMainNavi = self.selectedViewController;
    //
    if (visibleController) {
        //判断visibleController 是否有navi
        if (visibleController.navigationController==currentMainNavi) {
            [currentMainNavi popToRootViewControllerAnimated:false];
        }else {
            if (visibleController.navigationController) {
                if (visibleController.navigationController.qmui_isPresented) {
                    [visibleController dismissViewControllerAnimated:false completion:nil];
                }
            }else {
                if (visibleController.qmui_isPresented) {
                    [visibleController dismissViewControllerAnimated:false completion:nil];
                }
            }
            [currentMainNavi popToRootViewControllerAnimated:false];
        }
        if ([self.selectedViewController isKindOfClass:BChargeCashNavigationController.class]) {
            self.selectedIndex = 2;
        }
        if (needLogin) {
            [GSCommonLoginViewController presentToCommloginController:self];
        }
    }else {
        BCAppDelegate *appDelegate = (BCAppDelegate *)[UIApplication sharedApplication].delegate;
        [appDelegate toMainAction];
    }
}

/**
 首页切换区域后的通知
 */
- (void)homeRegionChangedNotification:(NSNotification *)noti {
    [self regionChangedUpdateControllers];
}
- (void)regionChangedUpdateControllers {
    if (_homeNavi) {
        _homeNavi = nil;
    }
    if (_industryNavi) {
        _industryNavi = nil;
    }
    [self setupCustoms];
}

/**
 语言切换
 */
- (void)userSettingLanguageChangedNotification:(NSNotification *)noti {
    [self settingLanguageChangedUpdateControllers];
}
- (void)settingLanguageChangedUpdateControllers {
    [[BCUserManager sharedUser] clearCacheData];
    if (_homeNavi) {
        _homeNavi = nil;
    }
    if (_industryNavi) {
        _industryNavi = nil;
    }
    if (_userCenterNavi) {
        _userCenterNavi = nil;
    }
    if (_conversionNavi) {
        _conversionNavi = nil;
    }
    if (_chargeCashNavi) {
        _chargeCashNavi = nil;
    }
    [self setupCustoms];
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
